/*
 * Calculates Seconds, executes shutdown.
 */
package shutdown;

import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;

/**
 *
 * @author Jens
 */
public class Manager {

	private String time;
	private Calendar now;
	private Calendar then;

	public Manager(String time) {
		this.time = time;
		this.then = new GregorianCalendar();
		then.set(Calendar.SECOND, 0);
	}

	/**
	 * Extracts time and calulates seconds.
	 * @return calculated seconds
	 */
	private long calcSeconds() throws Exception {
		//System.out.println("String="+time);

		/* Validate String and extract time */
		if (!time.matches("^[0-2]?\\d{1}[:\\-\\.\\s]?[0-5]{1}\\d{1}$")) {
			throw new Exception("Invalid Timeformat");
		}
		String[] hourminute;
		hourminute = time.split("[:\\-\\.\\s]?[0-5]{1}\\d{1}$");
		then.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hourminute[0]));
		hourminute = time.split("^[0-2]?\\d{1}[:\\-\\.\\s]?");
		then.set(Calendar.MINUTE, Integer.parseInt(hourminute[1]));

		/* Determine if it's the next day */
		now = new GregorianCalendar();
		if (now.getTimeInMillis() >= then.getTimeInMillis()) {
			then.set(Calendar.DAY_OF_YEAR, then.get(Calendar.DAY_OF_YEAR) + 1);
		}

		/* Calculate difference in seconds */
		return (then.getTimeInMillis() - now.getTimeInMillis()) / 1000;
	}

	/**
	 * Initiates shutdown
	 * @throws Exception
	 */
	public void shutdown() throws Exception {
		String seconds = Long.toString(calcSeconds());
		new ProcessBuilder("cmd", "/c", "shutdown", "/s", "/t", seconds).start();
	}

	/**
	 * Aborts shutdown
	 * @throws IOException
	 */
	public void abortShutdown() throws IOException {
		new ProcessBuilder("cmd", "/c", "shutdown", "/a").start();
	}
}
